<template>
  <div class="uploader">
    <h1>交通标志预测</h1>
    <input type="file" accept="image/*" @change="onSelectFile" />
    <div v-if="preview">
      <img :src="preview" alt="预览" />
    </div>
    <button :disabled="!file || loading" @click="doPredict">
      {{ loading ? '预测中...' : '开始预测' }}
    </button>
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    <div v-if="result" class="result">
      <p>类别 ID：{{ result.class_id }}</p>
      <p>置信度：{{ (result.confidence * 100).toFixed(2) }}%</p>
      <p>标签：{{ result.label }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const file = ref(null)
const preview = ref('')
const loading = ref(false)
const result = ref(null)
const error = ref(null)

function onSelectFile(event) {
  const f = event.target.files[0]
  if (!f) return
  file.value = f
  preview.value = URL.createObjectURL(f)
  result.value = null
  error.value = null
}

async function doPredict() {
  if (!file.value) return
  loading.value = true
  error.value = null
  try {
    const formData = new FormData()
    formData.append('file', file.value)
    const response = await fetch('http://127.0.0.1:5000/api/predict', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: formData
    })
    if (!response.ok) throw new Error('预测失败')
    result.value = await response.json()
  } catch (err) {
    console.error('Prediction error:', err)
    error.value = err.message || '预测失败，请检查网络或后端服务是否可用。'
    result.value = null
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.uploader {
  max-width: 600px;
  margin: 2rem auto;
  text-align: center;
  padding: 2rem;
  border: 2px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.uploader h1 {
  color: #2c3e50;
  margin-bottom: 2rem;
}

.uploader img {
  max-width: 100%;
  margin: 1rem 0;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

button {
  padding: 0.8rem 2rem;
  font-size: 1.1rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #3aa876;
}

input[type="file"] {
  margin: 1rem 0;
  padding: 1rem;
  border: 2px dashed #ccc;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

.result {
  margin-top: 2rem;
  padding: 1rem;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.error-message {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #ffebee;
  color: #c62828;
  border-radius: 4px;
  border: 1px solid #ffcdd2;
}
</style> 